package com.roy.royminidao.common.framework.lang.db;

/**
 * 
 * 数据库方言<br>
 * 〈功能详细描述〉
 * 
 * @author rong
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class DB2Dialect extends Dialect {

    /*
     * (non-Javadoc)
     * @see com.suning.scf.dao.base.Dialect#getLimitString(java.lang.String, int, int)
     */
    @Override
    public String getLimitString(String sql, int offset, int limit) {
        String sqlTemp = sql.toLowerCase();

        int startOfSelect = sqlTemp.indexOf("select");

        StringBuffer pagingSelect = new StringBuffer(sql.length() + 100).append(sql.substring(0, startOfSelect))
                .append("select * from ( select ").append(getRowNumber(sql));

        if (hasDistinct(sql)) {
            pagingSelect.append(" row_.* from ( ").append(sql.substring(startOfSelect)).append(" ) as row_");
        } else {
            pagingSelect.append(sql.substring(startOfSelect + 6));
        }
        pagingSelect.append(" ) as temp_ where rownumber_ ");

        // 设置获取记录的边界
        if (offset > 0) {
            pagingSelect.append("between " + offset + "+1 and " + (offset + limit));
        } else {
            pagingSelect.append("<= " + limit);
        }

        return pagingSelect.toString();
    }

    /**
     * 查看sql是否进行了distinct处理
     * 
     * @param sql
     * @return
     */
    private static boolean hasDistinct(String sql) {
        return sql.indexOf("select distinct") >= 0;
    }

    /**
     * 获取查询记录的行号
     * 
     * @param sql
     * @return
     */
    private static String getRowNumber(String sql) {
        StringBuffer rownumber = new StringBuffer(50);
        String sqlTemp = sql.toLowerCase();

        rownumber.append("rownumber() over(");

        int orderByIndex = sqlTemp.indexOf("order by");
        if (orderByIndex > 0 && !hasDistinct(sqlTemp)) {
            rownumber.append(sql.substring(orderByIndex));
        }
        rownumber.append(") as rownumber_,");

        return rownumber.toString();
    }
}
